package top.lidee.module.backendApi.twice.third.ali;

import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import top.lidee.framework.result.ResponseResult;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 张一恒
 * @version 1.0
 * @description: 阿里云oss测试
 * @date 2024/6/15 2:51
 */
@RestController("backendApiAliOssController")
@RequestMapping("/backendApi/oss")
public class AliOssController {

    @Value("${alibaba.access-key}")
    private String key;
    // 填写Bucket名称，例如examplebucket。
    @Value("${alibaba.oss.bucket}")
    private String bucket;
    // Endpoint以华东1（杭州）为例，其他Region请按实际情况填写。
    @Value("${alibaba.oss.endpoint}")
    private String endpoint;

    @Autowired
    private OSS oss;

    @RequestMapping(value = "/policy", method = RequestMethod.GET)
    public ResponseResult ossPolicy() {

        String host = "https://" + bucket + "." + endpoint;
        // 设置上传到OSS文件的前缀，可置空此项。置空后，文件将上传至Bucket的根目录下。
        String formatDir = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String formatDirTime = new SimpleDateFormat("HHmmss").format(new Date());
        String dir = formatDir + "/" + formatDirTime + "/" + UUID.randomUUID();

        // 创建OSSClient实例。
        Map<String, String> respMap = null;
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = oss.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
            String accessId = key;
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = oss.calculatePostSignature(postPolicy);

            respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
//             respMap.put("expire", formatISO8601Date(expiration));


        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        }

        return ResponseResult.okResultPage("data", respMap);
    }

    public static void main(String[] args) {

    }
}
